﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Drawing.Drawing2D;

using BrightIdeasSoftware;

using FCNS.KeepMoney.Configuration;
using FCNS.KeepMoney.UI;
using FCNS.KeepMoneyLibrary.Data;
using FCNS.KeepMoneyLibrary.Util;
using FCNS.KeepMoney.Util;

namespace FCNS.KeepMoney.Forms
{
    public partial class MainForm
    {
        void splitContainerLeft_SplitterMoved(object sender, SplitterEventArgs e)
        {
            configMainForm.LeftPanelWidth = splitContainerLeft.SplitterDistance;
        }

        void splitContainerChart_SplitterMoved(object sender, SplitterEventArgs e)
        {
            configMainForm.ChartHeight = splitContainerCenter.SplitterDistance;
        }

        private void OnListViewEntryColumnClick(object sender, ColumnClickEventArgs e)
        {
            foreach (AceColumn ac in configMainForm.ListViewEntryColumns)
            {
                if (ac.Sort)
                    ac.Sort = false;

                if (ac.ColumnIndex == e.Column)
                    ac.Sort = true;
            }
        }

        private void listViewEntry_CellRightClick(object sender, CellRightClickEventArgs e)
        {
            contextMenuStripEntry.Items.Clear();
            contextMenuStripEntry.Items.AddRange(TheEntryMenu);
            contextMenuStripEntry.Items.AddRange(TheAdditionMenu);

            UpdateUI(UIState.ConfigEditMenu);
        }


        //群组
        private void treeViewExGroup_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Action != (TreeViewAction.Collapse & TreeViewAction.Expand))
            {
                toolMenuFilter.Clear();
                ShowEntryData();
            }
        }

        private void OnGroupNodeClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (listViewEntry.GetItemCount() == 0 || !string.IsNullOrWhiteSpace(toolMenuFilter.Text))//图表NoOrmal筛选后和文本筛选后无法更新
                {
                    toolMenuFilter.Clear();
                    ShowEntryData();
                }
            }
            else if (e.Button == MouseButtons.Right)
            {
                treeViewExGroup.SelectedNode = e.Node;
                contextMenuStripGroup.Items.AddRange(TheGroupMenu);
                contextMenuStripGroup.Items.AddRange(TheAdditionMenu);
                UpdateUI(UIState.ConfigEditMenu);
            }
        }

        private void OnNewGroup(object sender, EventArgs e)
        {
            switch (configMainForm.UItype)
            {
                case UiType.Gtd:
                    TextForm s = new TextForm();
                    s.Init(LanguageUtil.时间管理, LanguageUtil.请输入类别名称, "");
                    s.UsedByGtd(null);
                    if (s.ShowDialog() == DialogResult.OK)
                    {
                        GtdGroupField group = new GtdGroupField(s.GetColor);
                        group.Name = s.GetText;
                        group.Checked = true;
                        group.AddRowToDataTable();

                        ListViewItemGtd g = new ListViewItemGtd();
                        g.Text = s.GetText;
                        g.Checked = true;
                        g.GroupField = group;
                        g.Color = group.ColorBorder;
                        listViewGtd1.Items.Add(g);
                        listViewGtd1.UpdateList();
                    }
                    break;

                case UiType.Money:
                    TreeNode node = new TreeNode(LanguageUtil.新群组);
                    GroupField gf;
                    if (treeViewExGroup.SelectedNode == null)
                    {
                        gf = new GroupField(0, node.Text, true);
                        treeViewExGroup.Nodes.Add(node);
                    }
                    else
                    {
                        GroupField group = (GroupField)treeViewExGroup.SelectedNode.Tag;
                        gf = new GroupField(group.Id, node.Text, group.IorE);
                        treeViewExGroup.SelectedNode.Nodes.Add(node);
                        treeViewExGroup.ExpandAll();
                    }

                    gf.AddNewRowToDataTable();
                    node.Tag = gf;
                    break;
            }
            UpdateUI(UIState.DataHasBeenChanged);
        }

        private void OnEditGroup(object sender, EventArgs e)
        {
            switch (configMainForm.UItype)
            {
                case UiType.Gtd:
                    TextForm sf = new TextForm();
                    sf.Init("时间管理", "请输入类别名称", "");
                    sf.UsedByGtd(listViewGtd1.Selected);
                    sf.ShowDialog();
                    OnGtdGroupEdit(listViewGtd1.Selected);
                    break;

                case UiType.Money:
                    GroupForm g = new GroupForm();
                    g.Init((GroupField)treeViewExGroup.SelectedNode.Tag);
                    if (g.ShowDialog() == DialogResult.OK)
                        ShowGroupField();

                    break;
            }
        }

        private void OnDeleteGroup(object sender, EventArgs e)
        {
            if (MessageBox.Show(LanguageUtil.此操作将移除其所属的所有账务记录_是否继续
                , "", MessageBoxButtons.YesNo) == DialogResult.No)
                return;

            switch (configMainForm.UItype)
            {
                case UiType.Gtd:
                    listViewGtd1.Selected.GroupField.Remove();
                    listViewGtd1.Items.Remove(listViewGtd1.Selected);
                    gtdView.UpdateGtdView(true);
                    break;

                case UiType.Money:
                    ((GroupField)treeViewExGroup.SelectedNode.Tag).Remove(true);
                    treeViewExGroup.Nodes.Remove(treeViewExGroup.SelectedNode);
                    ReLoadEntry();
                    break;
            }
            UpdateUI(UIState.DataHasBeenChanged);

            //MessageBox.Show(EntryField.GetEntryField.Count.ToString());
            //if (MessageBox.Show("", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
            //    listViewEntry.SetObjects(entryField);        
        }


        private void treeViewExGroup_ItemDrag(object sender, ItemDragEventArgs e)
        {
            DoDragDrop(e.Item, DragDropEffects.Move);
        }

        private void treeViewExGroup_DragDrop(object sender, DragEventArgs e)
        {
            TreeNode node = (TreeNode)e.Data.GetData(typeof(TreeNode));
            TreeNode targetNode = treeViewExGroup.GetNodeAt(treeViewExGroup.PointToClient(new Point(e.X, e.Y)));
            if (targetNode == null || node == targetNode)
                return;


            if (MessageBox.Show(LanguageUtil.确定要合并群组记录吗, "", MessageBoxButtons.YesNo) == DialogResult.No)
                return;

            GroupField tar = (GroupField)targetNode.Tag; GroupField sou = (GroupField)node.Tag;
            //不同支付类型的群组不能合并
            if (tar.IorE != sou.IorE)
            {
                MessageBox.Show(LanguageUtil.与目标群组的支付类型不相符_禁止合并);
                return;
            }

            if (sou.SearchAllSubField(tar.Id))
                sou.ChangeParentGroup(tar.Id);
            else
                targetNode.Parent.Nodes.Remove(node);

            foreach (EntryField field in entryField.FindAll(ef => { return ef.GroupId == sou.Id; }))
                field.GroupId = tar.Id;

            sou.Remove(false);
            ShowGroupField();
            Program.SaveKMD = true;
        }

        private void treeViewExGroup_DragEnter(object sender, DragEventArgs e)
        {
            object data = e.Data.GetData(typeof(TreeNode));
            if (data == null)
                e.Effect = DragDropEffects.None;
            else
                e.Effect = DragDropEffects.Move;


        }

        private void treeViewExGroup_DragOver(object sender, DragEventArgs e)
        {
            //TreeNode node = treeViewExGroup.GetNodeAt(treeViewExGroup.PointToClient(new Point(e.X, e.Y)));
            //if (node != null)
            //    node.BackColor = Color.Red;
        }


        //记录
        private void OnNewEntryInMenu(object sender, EventArgs e)
        {
            switch (configMainForm.UItype)
            {
                case UiType.Gtd:
                    break;

                case UiType.Money:
                    OnNewEntryButtonClick(sender, e);
                    break;
            }
        }

        private void OnEditEntry(object sender, EventArgs e)
        {
            EntryField field = GetSelectedEntry();
            if (field == null)
                return;

            decimal d = field.Money;

            EntryForm ef = new EntryForm();
            ef.Init(field);
            if (ef.ShowDialog() != DialogResult.OK)
                return;

            UpdateToolBarBottom();

            listViewEntry.RefreshObjects(entryField);
            UpdateChart(configPlot.DefaultChart);
        }

        private void OnDeleteEntry(object sender, EventArgs e)
        {
            switch (configMainForm.UItype)
            {
                case UiType.Gtd:
                    gtdView.RemoveTask(gtdView.SelectedTask);
                    break;

                case UiType.Money:
                    EntryField field = GetSelectedEntry();
                    if (field == null)
                        return;

                    EntryField ef = null;
                    if (field.EntryType == KMDEntryType.Transfer)
                        ef = entryField.Find(f => { return f.Id.ToString() == field.Mark; });

                    UpdateToolBarBottom();

                    field.Remove();
                    if (ef != null)
                        ef.Remove();

                    ShowEntryData();//要改善
                    break;
            }
        }


        //标记
        private void Tags_DropDownOpening(object sender, EventArgs e)
        {
            List<string> allTags = TagField.GetTagField;

            while (menuTags.DropDownItems.Count > 5)
                menuTags.DropDownItems.RemoveAt(5);

            foreach (string str in allTags)
                menuTags.DropDownItems.Add(str);
           
            EntryField field = (EntryField)listViewEntry.SelectedObject;
            ToolStripMenuItem newTag = (ToolStripMenuItem)menuTags.DropDownItems[0];
            ToolStripMenuItem removeTag = (ToolStripMenuItem)menuTags.DropDownItems[1];
            if (field == null)
            {
                newTag.Enabled = false;
                removeTag.Enabled = false;
                return;
            }
            else
            {
                newTag.Enabled = true;
                removeTag.Enabled = true;
            }

            List<string> oldTags = new List<string>(field.columnTag.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));

            while (newTag.DropDownItems.Count > 4)
                newTag.DropDownItems.RemoveAt(4);

            foreach (string str in allTags)
                if (!oldTags.Contains(str))
                    newTag.DropDownItems.Add(str);

            removeTag.DropDownItems.Clear();
            foreach (string str in oldTags)
                removeTag.DropDownItems.Add(str);
        }
        //查询
        private void Tags_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (menuTags.DropDownItems.IndexOf(e.ClickedItem) < 3)
                return;

            listViewEntry.SetObjects(entryField.FindAll(ef => { return ef.columnTag.Contains(e.ClickedItem.Text); }));
        }
        //增加
        private void AddTag_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem is ToolStripSeparator)
                return;

            EntryField field = (EntryField)listViewEntry.SelectedObject;
            List<string> existTags = new List<string>(field.columnTag.Split(','));

            List<string> newTags = new List<string>();
            if (e.ClickedItem.Name == "NewTag")//新增 标记
            {
                TextForm s = new TextForm();
                s.Init(LanguageUtil.新增标记, LanguageUtil.支持多标记输入_请用逗号分隔, "");
                if (s.ShowDialog() != DialogResult.OK)
                    return;

                if (s.GetText.Length == 0)
                    return;

                List<string> KMDataTags = TagField.GetTagField;
                foreach (string flag in s.GetText.Split(','))
                {
                    if (string.IsNullOrWhiteSpace(flag))
                        continue;

                    if (!KMDataTags.Contains(flag))
                        if (flag != LanguageUtil.借款 && flag != LanguageUtil.贷款)
                            TagField.NewTag(flag);

                    if (existTags.Contains(flag))
                        continue;

                    newTags.Add(flag);
                }
            }
            else
            {
                if (!existTags.Contains(e.ClickedItem.Text))//为选中的 Entry 行添加标记
                    newTags.Add(e.ClickedItem.Text);
            }

            existTags.AddRange(newTags);
            if (e.ClickedItem.Text != LanguageUtil.借款 && e.ClickedItem.Text != LanguageUtil.贷款)
                TagField.AddTag(newTags.FindAll(nt => { return nt != LanguageUtil.借款 && nt != LanguageUtil.贷款; }));

            string sg = string.Join(",", existTags.ToArray());
            field.columnTag = sg.StartsWith(",") ? sg.Remove(0, 1) : sg;
            listViewEntry.RefreshObject(listViewEntry.SelectedObject);

            if (configChart.DefaultChart == ChartType.Normal)
                UpdateChart(ChartType.Normal);

            UpdateUI(UIState.DataHasBeenChanged);
        }
        //删除
        private void DeleteTag_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            EntryField field = (EntryField)listViewEntry.SelectedObject;
            if (e.ClickedItem.Text != LanguageUtil.借款 && e.ClickedItem.Text != LanguageUtil.贷款)
                TagField.RemoveTag(e.ClickedItem.Text);

            List<string> s = new List<string>(field.columnTag.Split(','));
            s.Remove(e.ClickedItem.Text);
            field.columnTag = string.Join(",", s.ToArray());
            listViewEntry.RefreshObject(listViewEntry.SelectedObject);

            if (configChart.DefaultChart == ChartType.Normal)
                UpdateChart(ChartType.Normal);

            UpdateUI(UIState.DataHasBeenChanged);
        }

        private void OnRemoveAlertDate(object sener, EventArgs e)
        {
            ((EntryField)listViewEntry.SelectedObject).AlertDate = null;
            listViewEntry.RefreshObject(listViewEntry.SelectedObject);

            UpdateUI(UIState.DataHasBeenChanged);
        }


        private void OnShowHideForm(object sender, EventArgs e)
        {
            ChangeMainFormStatus();
        }

        void adsenseTimer_Tick(object sender, EventArgs e)
        {
            if (toolMenuAdsense.DropDownItems.Count < 2)
                return;

            ToolStripItem item = toolMenuAdsense.DropDownItems[toolMenuAdsense.DropDownItems.Count - 1];
            toolMenuAdsense.DropDownItems.Insert(0, item);
            toolMenuAdsense.Text = toolMenuAdsense.DropDownItems[0].Text;
            toolMenuAdsense.Tag = item.Tag;
        }
    }
}